<?php
/**
 *
 * @author eagle
 * @version 2014-7-29 上午10:46:49
 */
class  Ebayapi
{

    /**
     *
     * Description 得到账户邮件信息
     * @param $start  开始时间
     * @param $end 结束时间
     * $param $$token 账号API验证信息
     * @param $account 账号信息
     * @param $id errors_ackmessage表的id
     */
    public static function get_member_messages($start, $end, $token, $account, $id = 0)
    {

        require_once Kohana::find_file('vendor', 'ebayapi/eBaySession', 'php');
        require_once Kohana::find_file('vendor', 'ebayapi/xmlhandle', 'php');

	$counter 	= 0;

        $verb = 'GetMyMessages';
        $compatabilityLevel = 743;
        $siteID = 0;
        $user = 'vipadmin';

        $devID = "c61b9394-7572-43d2-88c3-b866a5326be3";
        $appID = "kokocomy-b225-4fe5-98a1-4bf38ceafbbf";
        $certID = "0f352688-cc85-494f-9526-0516aa9042cd";
        $serverUrl = "https://api.ebay.com/ws/api.dll";

        $requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>
            <GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">
            <RequesterCredentials>
            <eBayAuthToken>' . $token . '</eBayAuthToken>
            </RequesterCredentials>
            <StartTime>' . $start . '</StartTime>
            <EndTime>' . $end . '</EndTime>
            <DetailLevel>ReturnSummary</DetailLevel>
             <Pagination>
             <EntriesPerPage>199</EntriesPerPage>
             <PageNumber>1</PageNumber>
             </Pagination>
            </GetMyMessagesRequest>';
        $session = new eBaySession($token, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
        $responseXml = $session->sendHttpRequest($requestXmlBody);
        if (stristr($responseXml, 'HTTP 404') || $responseXml == '') {
            echo 'Error:A,id not found';
		return $counter;	
        }

        $responseDoc = new DomDocument();
        $responseDoc->loadXML($responseXml);
        $data = XML_unserialize($responseXml);
        $Ack = $data['GetMyMessagesResponse']['Ack'];
        //echo " status: ".$Ack." \n\r";

        /* 如果目录API返回失败，则写入失败表中。 */
        if ($Ack == '' || $Ack != 'Success') {
            $sql = "INSERT INTO errors_ackmessage(ebay_account,starttime,endtime,status,notes)
			VALUES('$account','$start','$end','0','Ack False')";
            DB::query(Database::INSERT, $sql)
                ->execute('ebaymail');
        }
        /* 如果执行失败的API返回记录成功后，则列新失败的状态 */
        if ($id > 0) {
            if ($Ack == 'Success') {
                $gg = "UPDATE errors_ackmessage SET status = 1 WHERE id='" . $id . "'";
                DB::query(Database::UPDATE, $sql)
                    ->execute('ebaymail');
            }
        }
        $FolorderID_list = $data['GetMyMessagesResponse']['Summary']['FolderSummary'];
	if(!is_array($FolorderID_list)){
		echo 'Account:'.$account;
		echo ',Taken:'.$token;

		print_r($data);
		exit;
	}		
        //$count_folorder     = count($FolorderID);

        foreach($FolorderID_list as $_folorderID) {

            /* 开始计算总页数 */
            $totalpages = ceil($_folorderID['TotalMessageCount'] / 199);
            $startpages = 1;
            /*开始加载对应目录下的Message信息 FolderID = 1 表示是 sent 文件夹*/
            if ($_folorderID['FolderID'] != 1) {
                while (true) {
                    $requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>
					<GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">
					<RequesterCredentials>
					<eBayAuthToken>' . $token . '</eBayAuthToken>
					</RequesterCredentials>
					<StartTime>' . $start . '</StartTime>
					<EndTime>' . $end . '</EndTime>
					<DetailLevel>ReturnHeaders</DetailLevel>
					<Pagination>
					<EntriesPerPage>199</EntriesPerPage>
					<PageNumber>' . $startpages . '</PageNumber>
					</Pagination>
					<FolderID>' . $_folorderID['FolderID'] . '</FolderID>
					</GetMyMessagesRequest>';
                    $session = new eBaySession($token, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
                    $responseXml = $session->sendHttpRequest($requestXmlBody);
                    if (stristr($responseXml, 'HTTP 404') || $responseXml == '') {
                        echo  'Error:B,id not found';
			return $counter;
                    }
                    $responseDoc = new DomDocument();
                    $responseDoc->loadXML($responseXml);
                    $data = XML_unserialize($responseXml);
                    $Ack = $data['GetMyMessagesResponse']['Ack'];
                    $Trans = $data['GetMyMessagesResponse']['Messages']['Message'];
                    $Sender = $data['GetMyMessagesResponse']['Messages']['Sender'];
                    if ($Sender != '') {
                        $Trans = array();
                        $Trans[0] = $data['GetMyMessagesResponse']['Messages']['Message'];
                    }

                    foreach ((array)$Trans as $Transaction) {
                        $Read = $Transaction['Read'] ? 1 : 0;
                        $HighPriority = $Transaction['HighPriority'];
                        $Sender = $Transaction['Sender'];
                        $MessageID = $Transaction['MessageID'];
                        $RecipientUserID = $Transaction['RecipientUserID'];
                        $Subject = mysql_escape_string($Transaction['Subject']);
                        $MessageType = $Transaction['MessageType'];
                        $Replied = $Transaction['Replied'];
                        $ItemID = $Transaction['ItemID'];
                        $ExternalMessageID = $Transaction['ExternalMessageID']; // 之前的id
                        $ReceiveDate = $Transaction['ReceiveDate'];
                        $ItemTitle = mysql_escape_string($Transaction['ItemTitle']);
                        $createtime1 = strtotime($ReceiveDate);
                        /*
                        $sql = "SELECT id
						FROM ebay_message
						WHERE message_id='" . $MessageID . "' AND ebay_account='" . $account . "'";
                        */
                        $sql = "SELECT id
                            FROM ebay_message
                            WHERE message_id='" . $MessageID . "'";
                        $ebay_message_tlist = DB::query(Database::SELECT, $sql)
                            ->execute('ebaymail')
                            ->as_array();

                        //数据库中不存在信息
                        if (count($ebay_message_tlist) == 0 && $MessageID > 1000) {

                            $status = 0;
                            if ($Replied == 'false') {
                                $status = 1;
                            }

                            $verb = 'GetMyMessages';
                            $requestXmlBody = '<?xml version="1.0" encoding="utf-8"?>
							<GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">
							<DetailLevel>ReturnMessages</DetailLevel>
							<RequesterCredentials>
							<eBayAuthToken>' . $token . '</eBayAuthToken>
							</RequesterCredentials>
							<MessageIDs><MessageID>' . $MessageID . '</MessageID>
							</MessageIDs>
							</GetMyMessagesRequest> ';
                            $session = new eBaySession($token, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
                            $responseXml = $session->sendHttpRequest($requestXmlBody);
                            $data = XML_unserialize($responseXml);


                            $Body = mysql_escape_string($data['GetMyMessagesResponse']['Messages']['Message']['Text']);
                            $status = 0;
                            $forms = 0;
                            if ($Sender == 'eBay') {
                                $forms = 2;
                            }
                            if ($HighPriority == 'true') {
                                $forms = 3;
                            }
                            $classid = '0';
                            if ($Sender != 'eBay') {
                                $first = substr($Sender, 0, 1);
                                $sql = "SELECT id
								FROM ebay_messagecategory
								WHERE rules LIKE '%$first%'
								AND ebay_account LIKE '%$account%'
								AND ebay_user ='$user'
								LIMIT 1";
                                $ebay_messagecategory_list = DB::query(Database::SELECT, $sql)
                                    ->execute('ebaymail')
                                    ->as_array();

                                if (count($ebay_messagecategory_list) > 0) {
                                    $classid = $ebay_messagecategory_list[0]['id'];
                                }
                            }
                            $QuestionType = 'Default';
                            $SenderEmail = '';
                            $starttime = '';
                            $endtime = '';
                            $price = '';
                            $mctime = time();
                            $ViewItemURL = '';
                            $sql = "INSERT INTO `ebay_message` (`message_id` , `message_type` , `question_type` ,
							`recipientid` , `sendmail` , `sendid` , `subject` , `body` , `itemid` , `starttime` ,
							`endtime` , `currentprice` , `title` , `createtime` , `ebay_user` , `add_time` ,
							`itemurl` , `ebay_account`,`classid`,`createtime1`,`status`,`forms`,`Read`,`ExternalMessageID`)
								VALUES ('" . $MessageID . "', '" . $MessageType . "' ,'" . $QuestionType . "' , '" . $RecipientUserID . "' ,
										'" . $SenderEmail . "' , '" . $Sender . "' , '" . $Subject . "' , '" . $Body . "' , '" . $ItemID . "',
										'" . $starttime . "' , '" . $endtime . "' , '" . $price . "' , '" . $ItemTitle . "' , '" . $ReceiveDate . "' ,
										'" . $user . "' , " . $mctime . ",'" . $ViewItemURL . "','" . $account . "','" . $classid . "','" . $createtime1 . "',
										'" . $status . "','" . $forms . "','" . $Read . "','" . $ExternalMessageID . "') ";
                            DB::query(Database::INSERT,$sql)->execute('ebaymail');
				$counter++;
                        } else {
                            //echo $Sender . ' exit <br>';
                        }

                    }

                    $startpages++;
                    if ($startpages > $totalpages) {
                        break;
                    }
                }
            }
        }

        $sql = "UPDATE ebay_account SET message_updtime='".$end."' WHERE ebay_account='".$account."'";
        DB::query(Database::UPDATE, $sql)->execute('ebaymail');

	return $counter;
    }


}
